import 'dart:async';

import 'package:find_friend/common/alert_tool.dart';
import 'package:find_friend/const/const.dart';
import 'package:find_friend/network/network.dart';
import 'package:find_friend/pages/login&register/login_textfield.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class ForgetPasswordPage extends StatefulWidget {

  final String phone;

  const ForgetPasswordPage({Key key, this.phone}) : super(key: key);

  @override
  _ForgetPasswordPageState createState() => _ForgetPasswordPageState();
}

class _ForgetPasswordPageState extends State<ForgetPasswordPage> {

  final _pwdFoucs = FocusNode();
  final _codeFoucs = FocusNode();
  String code = "";
  String rightCode = "";
  bool _isverify_code = true;
  final _scaffoldKey = GlobalKey<ScaffoldState>();
  final TextEditingController _controller = TextEditingController();
  final TextEditingController _codeController = TextEditingController();
  int resentCode = 59;
  String resetString = "";
  Timer _timer;

  @override
  void initState() {
    super.initState();

    _sendSMS();
  }

  @override
  void dispose() {
    _controller.dispose();
    _codeController.dispose();
    _stopTimer();
    super.dispose();
  }


   _beginTimer() {
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      print("$resetString");
      if(resentCode == 1) {
        _stopTimer();
        resentCode = 59;
        setState(() {
          resetString = "";
        });
      } else {
        resentCode -= 1;
        setState(() {
          resetString = "($resentCode)";
        });
      }
    });
  }

  _stopTimer() {

    _timer?.cancel();
    _timer = null;
  }

   void _sendSMS() {
    Networktool.request(API.code, params: {"mobile":widget.phone,"event": "resetpwd"},success:(data){
      print(data);
      if(data["data"] != null) {
        rightCode = data["data"]["code"].toString();
        _beginTimer();
      } else {
        AlertTool.showToast(data["msg"]);
      }
    }, fail: (data){
      AlertTool.showToast(data);
    });
  }

  _requestModPassword() {
    if(_codeController.text.length == 0) {
      AlertTool.showToast("请输入验证码");
      return;
    }
    if(_codeController.text != rightCode) {
      AlertTool.showToast("验证码有误");
      return;
    }
    Networktool.request(API.resetpwd, params: {"mobile":widget.phone, "code":_codeController.text, "new_pwd":_controller.text, "event":"resetpwd"},success:(data){
      AlertTool.showToast(data["msg"]);
      Navigator.of(context).pop();
    }, fail: (data){
      AlertTool.showToast(data);
    });
  }

  String _getCodeString(int index) {
    if(index < code.length) {
      return code[index];
    } else {
      return "";
    }
  }

  _initVerifyCode() {
    TextStyle style = instanceTextStyle(15, Colors.black, fontWeight: FontWeight.bold);
    return Stack(
      children: [
        Container(
          padding: const EdgeInsets.only(top: 30),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text("输入验证码", style: instanceTextStyle(13, Colors.black, fontWeight: FontWeight.bold),),
              SizedBox(height: 9.5,),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: List.generate(4, (index) => 
                Container(
                    width: 50,
                    height: 40,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(20),
                      border: Border.all(color: _getCodeString(index) == "" ? Colors.black : (_isverify_code ? APP_main_color : APP_verify_error_color), width: 1.5)
                    ),
                    child: Text(_getCodeString(index), style: style),
                  )),
              ),
              Container(
                padding: const EdgeInsets.only(top: 20),
                alignment: Alignment.centerRight,
                child: GestureDetector(
                  child: RichText(
                    text: TextSpan(
                      children: [
                        TextSpan(text: "重新发送验证码",style: instanceTextStyle(11,APP_main_color, fontWeight: FontWeight.bold, decoration: TextDecoration.underline)),
                        TextSpan(text: resetString,style: instanceTextStyle(11, APP_main_color, fontWeight: FontWeight.bold)),
                      ]
                    ),
                  ),
                  onTap: (){
                    if(resentCode == 59) {
                      _sendSMS();
                    }
                  },
                ),
              )
            ],
          ),
        ),
        Container(
          height: 100,
          child: TextField(
            controller: _codeController,
            showCursor: false,
            maxLength: 4,
            inputFormatters: [WhitelistingTextInputFormatter.digitsOnly],
            focusNode: _codeFoucs,
            style: TextStyle(color: Colors.transparent),
            keyboardType: TextInputType.number,
            decoration: InputDecoration(
              border: InputBorder.none,
              counterText: "",
            ),

            onChanged: (str){
              setState(() {
                code = str;
                if(str.length == 4) {
                  _isverify_code = str == rightCode;
                } else {
                  _isverify_code = true;
                }
              });
              if(_isverify_code == false && str.length == 4) {
                AlertTool.showToast("验证码有误");
              }
            },
          ),
        )
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: Colors.white,
      key: _scaffoldKey,
      resizeToAvoidBottomPadding: false,
      body: SafeArea(
          child: GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: (){
              _pwdFoucs.unfocus();
              _codeFoucs.unfocus();
            },
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                padding: const EdgeInsets.only(right: 15, left: 5),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    IconButton(
                      icon: Image.asset("assets/zhuce-fanhui.png"),
                      onPressed: () => Navigator.of(context).pop(),
                    ),
                    Column(
                      children: [
                        Image.asset("assets/zhuce-kefu.png"),
                        Text("客服",style: instanceTextStyle(9, APP_font_black),)
                      ],
                    )
                  ],
                ),
              ),
              SizedBox(height: size.width * 0.1,),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 40),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      child: Text("忘记密码", style: instanceTextStyle(
                        22,
                        Colors.black,
                        fontWeight: FontWeight.bold
                      )),
                    ),
                    SizedBox(height: 33),
                    RichText(
                      text: TextSpan(
                        children: [
                          TextSpan(text: widget.phone, style: instanceTextStyle(15, APP_main_color, fontWeight: FontWeight.bold)),
                          TextSpan(text: "请重新设置新密码", style: instanceTextStyle(11, APP_font_grey)),
                        ]
                      ),
                    ),
                    _initVerifyCode(),
                    SizedBox(height: 30,),
                    Text("重置您的密码，不要再忘记了哦亲～", style: instanceTextStyle(11, APP_font_grey),),
                    SizedBox(height: 40,),
                    LoginTextField(
                      controller: _controller,
                      obscureText: true,
                      placeholder: "输入密码（6位以上）",
                      focusNode: _pwdFoucs,
                    ),
                    
                  ],
                )
              ),
              
              Spacer(),
              Center(
                child: GestureDetector(
                  onTap: (){
                    _requestModPassword();
                  },
                  child: Padding(
                    padding: const EdgeInsets.only(bottom: 30),
                    child: Column(
                      children: [
                        Image.asset("assets/zhuce-xia.png"),
                        SizedBox(height: 20,),
                        Text("下一步", style: instanceTextStyle(14, APP_font_black),)
                      ],
                    ),
                  ),
                ),
              ),
            ],
        ),
          ),
      )
    );
  }
}